var db = require('../db/index.js').get();
var utils = require('../utils.js');
// console.log(utils);
var imageCl = db.image;
async function init() {
    var failed = [];
    var q = {
        $or: [
            {'baseInfo.width': -1 },
            {'baseInfo.height': -1},
            {'baseInfo.aspectRatio': { $exists: false }},
            {'baseInfo.aspectRatio': 0}
        ]
    }
    var c = await imageCl.countDocuments(q);
    for (var i = 0; i < c; i++) {
        var originalName, img;
        try {
            var s = Date.now();
            img = (await imageCl.find(q).skip(failed.length).limit(1))[0];
            originalName = utils.getOriginalName(img.baseInfo.src);
            if (img.baseInfo.width == -1 || img.baseInfo.height == -1) {
                var size = await utils.getImageSize(originalName);
                img.baseInfo.width = size.width;
                img.baseInfo.height = size.height;
            }
            img.baseInfo.aspectRatio = img.baseInfo.width / img.baseInfo.height;
            await img.save();
            console.log('set size', i, '--', c, originalName, '->\n\t',
                img.baseInfo.width + 'x' + img.baseInfo.height + '-' + img.baseInfo.aspectRatio, "\n\t::", Date.now() - s + 'ms');
        } catch (e) {
            console.log('failed', i, '--', c, originalName, e.message);
            failed.push({i, originalName, Error: e.message});
            await img && img.save();
        }
    }
    return failed;
}

if (!module.parent) {
    init()
} else {
    module.exports = {
        init
    };
}